#include "WidgetsMenu.h"
#include "Router.h"

#define if_enable(k) (k & _cfg)

widgetsMenu::widgetsMenu(QWidget* parent)
: QMenu(parent)
, _cfg(0)
{
}

void widgetsMenu::setup()
{
    QMenu* add = addMenu("Add");

    connect(add, SIGNAL(triggered(QAction *)), this, SLOT(onAddAction(QAction *)));

    auto all = Router::getInstance().getAllType();

    for (const auto& type : all)
    {
        if (type.isEmpty() || type.isNull())
            add->addSeparator();
        else
            add->addAction(type);
    }

    QAction* addf = addAction("Add From");
    addf->setEnabled(if_enable(kAddFrom));
    addf->setData(kAddFrom);

    QAction* del = addAction("Delete");
    del->setEnabled(if_enable(kDelete));
    del->setData(kDelete);

    QAction* copy = addAction("Copy");
    copy->setIcon(QIcon(":/XXEditor/images/copy.png"));
    copy->setEnabled(if_enable(kCopy));
    copy->setData(kCopy);

    QAction* paste = addAction("Paste");
    paste->setIcon(QIcon(":/XXEditor/images/paste.png"));
    paste->setEnabled(if_enable(kPaste));
    paste->setData(kPaste);

    QAction* save = addAction("Save To File");
    save->setEnabled(if_enable(kSave));
    save->setData(kSave);

    QAction* code = addAction("Copy Lua Code");
    code->setEnabled(if_enable(kCode));
    code->setData(kCode);

    QAction* codec = addAction("Copy C++ Code");
    codec->setEnabled(if_enable(kCodeCpp));
    codec->setData(kCodeCpp);

    connect(this, SIGNAL(triggered(QAction *)), this, SLOT(onActionTriggered(QAction *)));
}

widgetsMenu* widgetsMenu::create(QWidget* parent)
{
    widgetsMenu* menu = new widgetsMenu(parent);
    return menu;
}

void widgetsMenu::showAtPos()
{
    setup();
    exec(QCursor::pos());
}

void widgetsMenu::onActionTriggered(QAction* a)
{
    emit onTouch(a->data().toInt());
}

void widgetsMenu::onAddAction(QAction* a)
{
    emit onAdd(a->text());
}

widgetsMenu* widgetsMenu::cfg(cfg_key k, bool e)
{
    if (e)
        _cfg |= k;
    else
        _cfg &= ~k;
    return this;
}

